package com.kingoe.mybatisdj.shard.strategy;

import com.kingoe.mybatisdj.shard.interceptor.ITableShardStrategy;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * id 取模策略，模拟两张表
 * @author jinwu
 */
@Slf4j
@Component
public class TableShardStrategyId implements ITableShardStrategy {

    private final ConcurrentHashMap<Long, String> tableStrategyCache = new ConcurrentHashMap<>();

    @Value("#{${shard.strategy.table_map}}")
    private Map<Long, Long> tableMap;
    @Value("#{${shard.strategy.count}}")
    private long tableCount;

    @Override
    public String generateTableName(String tableNamePrefix, Object value) {
        verificationTableNamePrefix(tableNamePrefix);
        if (value == null || StringUtils.isBlank(value.toString())) {
            throw new RuntimeException("value is null");
        }
        long id = Long.parseLong(value.toString());
        String tableName = tableStrategyCache.get(id);
        if (StringUtils.isBlank(tableName)) {
            tableName = tableNamePrefix + "_" + tableMap.getOrDefault(id, id % tableCount);
            tableStrategyCache.putIfAbsent(id, tableName);
        }
        //此处可以缓存优化
        return tableStrategyCache.get(id);
    }
}
